# -*- coding: UTF-8 -*-
from tools.Initialization import DEEPFOS_HOST, APP_DB_NAME, DATABASE_INFO, AUTO_CREATE, SPACEID, APPID
from tools.Request_General import get_all_module_id
from pyLib.LogManage import LOG
from pyLib.databaseManage import SYS_DATABASE, ACCOUNT_DATABASE
from application.general_login import USER
from application.system_server_api import SystemServer
from application.space_server_api import SpaceServer
from application.app_server_api import AppServer
from tools.encryption import get_md5

# 初始化空间名 应用名
sp_name = APP_DB_NAME + get_md5(DEEPFOS_HOST)[-3::] + "自动化"
bak_name = APP_DB_NAME + get_md5(get_md5(DEEPFOS_HOST))[-3::] + "自动化"
app_name = APP_DB_NAME + get_md5(DEEPFOS_HOST)[-3::] + "9"
# 初始化数据库连接信息
HOST_DB, HOST_PORT, HOST_USER, HOST_PWD = DATABASE_INFO.values()
create_space_body = {"customDataSource": True, "spaceName": sp_name, "jdbcType": "mysql", "dbName": APP_DB_NAME,
                     "databaseUrl": HOST_DB, "port": HOST_PORT, "jdbcUserName": HOST_USER, "jdbcPassword": HOST_PWD,
                     "tenantCode": "default"}
create_app_body = {"customDataSource": True, "customLogo": False, "appName": app_name, "dbName": APP_DB_NAME,
                   "description": app_name + '_app', "logoPath": "", "jdbcPassword": HOST_PWD, "appType": "DEEPFOS",
                   "jdbcType": "mysql", "jdbcUrl": HOST_DB, "jdbcUserName": HOST_USER, "port": HOST_PORT}


class CREATE:

    def search_system(self, is_register: bool = False, spa_name=sp_name, spa_body=None, app_body=None):
        """
        is_register : 是否强制注册所有组件 默认注册
        查询automation空间是否存在，若不存在则创建并注册所有组件，若存在则返回查询的空间 应用 ID，注册所有组件
        :return: 空间ID 应用ID cookie 组件注册状态
        """
        token, user, cookie = USER().login(get_cookies=True)
        LOG.info("系统登录： user-{}、cookie-{}".format(user, str(cookie)))
        code = get_enterprise_code(user)  # 获取默认企业code
        # 获取企业id
        enterprise_id = ACCOUNT_DATABASE.execute_sql(
            f"SELECT id FROM enterprise_info WHERE enterprise_code='{code}'"
        )[0][0]
        # 如果自动创建标识为True
        if AUTO_CREATE:
            if app_body is None:
                app_body = create_app_body
            if spa_body is None:
                create_space_body.update({"tenantCode": code})
                create_space_body.update({"spaceName": f"{spa_name}_{code}"})
                spa_body = create_space_body
            results = SYS_DATABASE.get_db_data(table="sys_space_info", show_list=["id"],
                                            condition=f"space_name='{spa_name}_{code}' and tenant_code='{code}'")
            if len(results) == 0:  # 如果空间不存在
                # 创建空间
                space_id = self.init_environment(user_id=user, space_body=spa_body, ck=cookie)
                # 注册组件
                self.init_environment_modules(space_id, user, cookie)
                # 创建app
                app_id = self.init_environment_app(space_id=space_id, user_id=user, app_body=app_body, ck=cookie)
            else:
                space_id = results[0][0]
                if is_register:
                    # 注册组件
                    self.init_environment_modules(space_id, user, cookie)
                results_app = SYS_DATABASE.get_db_data(table="sp_app_info", show_list=["id"],
                                                    condition=f"space_id='{space_id}' and app_name='{app_name}'")
                if len(results_app) == 0:  # 如果app不存在
                    # 创建app
                    app_id = self.init_environment_app(space_id, user, app_body, cookie)
                else:
                    app_id = results_app[0][0]
            space_name = f"{spa_name}_{code}"
        else:
            space_id, app_id = SPACEID, APPID
            assert space_id, "space_id为空"
            assert app_id, "app_id为空"
            space_name = SYS_DATABASE.execute_sql(
                f"SELECT space_name FROM sys_space_info WHERE id='{space_id}'"
            )[0][0]
        return space_id, app_id, cookie, user, enterprise_id, space_name

    @staticmethod
    def init_environment(user_id, space_body, ck):
        """
        创建空间
        :return: space_id
        """
        space_id = ""
        # 创建空间
        r_create_space = SystemServer(headers={"user": str(user_id), "cookie": ck}).create_space(
            payload=space_body).json()
        LOG.info("创建空间：{}、{}".format(str(r_create_space), str(space_body)))
        if r_create_space.get("status") is True:
            space_id = r_create_space.get("data")
        return space_id

    @staticmethod
    def init_environment_app(space_id, user_id, app_body, ck):
        """
        创建APP
        :param space_id:
        :param user_id:
        :param app_body:
        :param ck: cookie
        :return:
        """
        # 创建APP
        r_create_app = SpaceServer(headers={"cookie": ck, "space": space_id, "user": str(user_id)}).app_add(
            payload=app_body).json()
        LOG.info("创建APP：{}、{}".format(str(r_create_app), str(app_body)))
        if r_create_app.get("status") is True:
            return r_create_app.get("data")

    @staticmethod
    def init_environment_modules(space_id, user_id, ck, db_type="DAT_MYSQL"):
        """
        查询组件  注册组件
        :param user_id:
        :param space_id:
        :param ck:
        :param db_type:
        :return:
        """
        try:
            sp_server = SpaceServer({"space": space_id, "user": str(user_id), "cookie": ck})
            r_search_modules = sp_server.all_list().json()  # 组件查询
            mod_lists = get_all_module_id(r_search_modules)  # 组件列表
            results_ = SYS_DATABASE.execute_sql(
                "SELECT a.module_id, b.module_id mods, b.protocol, b.protocol_version "
                "from sys_module_relation_protocol a join sys_module_protocol b on"
                " a.relation_protocol=b.protocol WHERE b.module_id like '{}%'".format(db_type))
            modules_list = [{"moduleId": mod} for mod in mod_lists]  # 生成组件注册数据
            r = sp_server.module_register(payload=modules_list)
            LOG.info(f"组件注册:{r.text}")
            # 默认绑定组件版本
            for i in results_:
                sp_server.quote_rel_batch_add(
                    pay=[{"quoteTargetModuleId": i[1], "protocolSplitJoint": i[2] + "_" + str(i[3]),
                          "quoteByModuleId": i[0]}])
            return True
        except Exception as e:
            LOG.info("组件注册失败：{}".format(str(e)))
            return False

    @staticmethod
    def del_element(space_id, app_id, token, user_id, ck, del_info: list = None):
        """
        删除元素
        :return:
        """
        del_element = [{"folderId": del_info[0], "elementName": del_info[1], "elementType": del_info[2]}]
        r_search_modules = AppServer(headers={"app": app_id, "space": space_id, "token": token,
                                              "user": str(user_id),
                                              "cookie": ck}).delete_element(payload=del_element).json()
        return r_search_modules.get("status")


def get_enterprise_code(user_, sql=None):
    """
    获取默认企业code
    """
    if sql is None:
        sql = "select enterprise_code from user_enterprise_pk where user_id='{}' and default_enterprise=1".format(user_)
    try:
        code = ACCOUNT_DATABASE.execute_sql(sql)[0][0]
    except Exception as e:
        return "default"
    LOG.info("默认企业code：{}".format(str(code)))
    return code


SPACE_ID, APP_ID, COOKIE, USER_ID, ENTERPRISE_ID, SPACE_NAME = CREATE().search_system()

if __name__ == '__main__':
    print(SPACE_ID, APP_ID, COOKIE, USER_ID, SPACE_NAME, ENTERPRISE_ID)
    print(SPACE_ID, '\n', APP_ID)
